import React, {PureComponent} from 'react';
import {connect} from 'dva';
import moment from 'moment'
import {
    Button,
    Card,
    DatePicker,
    Cascader,
    Form,
    Icon,
    InputNumber,
    Input,
    Modal,
    Radio,
    Select,
    Tooltip,
    Upload
} from 'antd';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './style.less';
import UEditor from '../../ueditor/UMEditor';

const FormItem = Form.Item;
const {Option} = Select;
const {RangePicker} = DatePicker

const {TextArea} = Input;

@connect(state => ({
    advert: state.advert,
}))
@Form.create()
export default class AdvertAdd extends PureComponent {
    state = {
        thumbUrl: '',
        previewVisible: false,
        previewImage: '',

        fileList: [],
    }

    componentDidMount() {

    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                values.start_at = moment(values.show_time[0]).format('YYYY-MM-DD HH:mm:ss')
                values.end_at = moment(values.show_time[1]).format('YYYY-MM-DD HH:mm:ss')
                this.props.dispatch({
                    type: 'advert/add',
                    payload: values,
                    callback: () => {
                        this.props.form.resetFields();
                        this.setState({
                            thumbUrl: '',
                        });
                    },
                });
            }
        });
    }

    handleCancel = () => this.setState({previewVisible: false})

    handlePreview = (file) => {
        console.log(file);
        this.setState({
            previewImage: file.response.data.url,
            previewVisible: true,
        });
    }

    thumbUpload = (info) => {
        if (info.file.status === 'done') {
            const thumbUrl = info.file.response.data.url;
            this.setState({
                thumbUrl,
            });
            return info.file.response.data.file;
        }
    }
    photosChange = ({fileList}) => {
        this.setState({fileList});
        return this.state.fileList;
    }
    beforeUpload = () => {

    }

    render() {
        const {advert: {options,types, loading}} = this.props;
        const {getFieldDecorator} = this.props.form;
        const thumbUrl = this.state.thumbUrl;
        const {previewVisible, previewImage, fileList} = this.state;
        const uploadButton = (
            <div>
                <Icon type="plus"/>
                <div className="ant-upload-text">上传图片</div>
            </div>
        );
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 7},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 17},
                md: {span: 14},
            },
        };
        const submitFormLayout = {
            wrapperCol: {
                xs: {span: 24, offset: 0},
                sm: {span: 10, offset: 7},
            },
        };
        const rangeConfig = {
            rules: [{type: 'array', required: true, message: '请选择展示时间'}],
        };
        return (
            <PageHeaderLayout title="新增轮播" content="新增广告，下列的所有内容均需填写">
                <Card bordered={false}>
                    <Form
                        onSubmit={this.handleSubmit}
                        hideRequiredMark
                        style={{marginTop: 8}}
                    >
                        <FormItem
                            {...formItemLayout}
                            label="缩略图"
                        >
                            <div className="dropbox">
                                {getFieldDecorator('thumb', {
                                    valuePropName: 'thumb',
                                    getValueFromEvent: this.thumbUpload,
                                    rules: [{
                                        required: true,
                                        message: '请上传缩略图',
                                    }],
                                })(
                                    <Upload.Dragger showUploadList={false} name="file"
                                                    action={`/api/upload?token=${sessionStorage.getItem('access_token')}`}>
                                        {thumbUrl ? <img src={thumbUrl} alt="" className={styles.thumb}/> :
                                            <div>
                                                <p className="ant-upload-drag-icon">
                                                    <Icon type="inbox"/>
                                                </p>
                                                <p className="ant-upload-text">点击或拖拽上传</p>
                                            </div>}
                                    </Upload.Dragger>
                                )}
                            </div>
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label={
                                <span>
                  广告类别
                  <em className={styles.optional}>
                      &nbsp;
                      <Tooltip title="选择需要添加到的类别">
                      <Icon type="info-circle-o" style={{marginRight: 4}}/>
                    </Tooltip>
                  </em>
                    </span>
                            }
                        >
                            {getFieldDecorator('type', {initialValue: 'index_left'})(
                                <Select>
                                    {options.map((item) => (<Option key={item.value}>{item.label}</Option>))}
                                </Select>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label={
                                <span>
                  链接类型
                  <em className={styles.optional}>
                      &nbsp;
                      <Tooltip title="链接类型分为带参数和不带参数两种。详情页面都带参数。需要指定具体的id，才能跳转">
                      <Icon type="info-circle-o" style={{marginRight: 4}}/>
                    </Tooltip>
                  </em>
                    </span>
                            }
                        >
                                <Select onChange={(value)=>{
                                    console.log(value)
                                    this.props.form.setFieldsValue({link:value})
                                }}>
                                    {types.map((item) => (<Option key={item.link}>{item.title}</Option>))}
                                </Select>

                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="跳转链接"
                        >
                            {getFieldDecorator('link', {
                                rules: [{
                                    required: true, message: '请输入跳转链接',
                                }],
                            })(
                                <Input/>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="广告简介"
                        >
                            {getFieldDecorator('description', {
                                rules: [{
                                    required: true, message: '请输入广告简介',
                                }],
                            })(
                                <TextArea style={{minHeight: 32}} placeholder="请输入广告简介" rows={4}/>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="优先级"
                        >
                            {getFieldDecorator('sort', {})(
                                <InputNumber min={0}/>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="展示时间"
                        >
                            {getFieldDecorator('show_time', rangeConfig)(
                                <RangePicker/>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="状态"
                        >
                            {getFieldDecorator('status', {initialValue: 1})(
                                <Radio.Group>
                                    <Radio value={0}>禁用</Radio>
                                    <Radio value={1}>启用</Radio>
                                </Radio.Group>
                            )}
                        </FormItem>

                        <FormItem {...submitFormLayout} style={{marginTop: 32}}>
                            <Button type="primary" htmlType="submit" loading={loading}>
                                提交
                            </Button>
                            <Button onClick={() => {
                                this.props.form.resetFields();
                            }} style={{marginLeft: 8}}>重置</Button>
                        </FormItem>
                    </Form>
                </Card>
                <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="图片预览" style={{width: '100%'}} src={previewImage}/>
                </Modal>
            </PageHeaderLayout>
        );
    }
}
